package common

import (
	"sync"
	"time"
)

var matchIds sync.Map
var matchChan, checkChan chan int
var matchIdArr []int64

func InitWork() {
	//matchIds = sync.Map{}
	//matchChan = make(chan int, 10)
	//checkChan = make(chan int, 10)
	//matchIdArr  = make([]int64,0)
	//if config.GetConf().Api.Port != 8085 {
	//	return
	//}
	//checkMatch()
	//loadMatch()
}
func loadMatch() {
	ticker := time.NewTicker(time.Hour * 1)
	go func() {
		for true {
			select {
			case <-ticker.C:
				GetMatch()
			}
		}
		ticker.Stop()
	}()
}
func getIds(p sync.Map) []int64 {
	var rs = make([]int64, 0)
	p.Range(func(key, value interface{}) bool {
		rs = append(rs, value.(int64))
		return true
	})
	return rs
}
func GetMatch() {
	//var goods goodsrecordmodel.GoodsRecord
	//rows,_ :=goodsrecordmodel.GetInstance().GetDb().Select("id,end_time").Where("end_time > ?",time.Now().Unix()).NotIn("id",getIds(matchIds)).Rows(&goods)
	//defer rows.Close()
	//for rows.Next(){
	//	err := rows.Scan(&goods)
	//	if err != nil {
	//		utils.Log(nil, "get match", err)
	//		continue
	//	}
	//	matchIds.Store(goods.Id,goods.EndTime)
	//	matchIdArr = append(matchIdArr,goods.Id)
	//}
	//if len(matchIdArr) >0{
	//	checkChan <-1  //通知有新任务
	//}

}
func moreMatch() {
	if rs, _ := <-matchChan; rs > 0 {
		GetMatch()
	}
}

// 开奖
func handMatch() {
	//if len(matchIdArr) >0{
	//	var id= matchIdArr[0]
	//	rs,_ :=matchIds.LoadAndDelete(id)
	//	if rs.(int64) >= time.Now().Unix(){
	//		var rs = v1.MatchRes{
	//			Id: id,
	//			Res: "",
	//		}
	//		Produce(CaculateMatch,rs,0)
	//		if len(matchIdArr) >1{
	//			matchIdArr = matchIdArr[1:]
	//		}else{
	//			matchIdArr = make([]int64,0)
	//			moreMatch()
	//			matchChan <-1
	//			if rs,_ := <- checkChan; rs >0{
	//				handMatch()
	//			}
	//		}
	//	}
	//}

}
func checkMatch() {
	ticker := time.NewTicker(time.Millisecond * 300)
	go func() {
		for true {
			select {
			case <-ticker.C:
				handMatch()
			}
		}
		ticker.Stop()
	}()
}
